package com.xiaomage.handlerdemo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import kotlinx.android.synthetic.main.activity_handler_thread.*

class HandlerThreadActivity : AppCompatActivity() {
    private val handlerThread=HandlerThread("xiaomage")
    //子线程handler
    private var sonHandler:Handler?=null
    //主线程Handler
    private var mainHandler:Handler=Handler()
    //用来判断判断是否还有继续循环
    private var needUpdate=false
    //判断的常量
    private val MSG_UPDATE_NUMBER=0x110
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handler_thread)
        handlerThread.start()
        sonHandler=object:Handler(handlerThread.looper){
            override fun handleMessage(msg: Message) {
                updateInfor()
                if(needUpdate){
                    sonHandler?.sendEmptyMessage(MSG_UPDATE_NUMBER)
                }
            }
        }
    }

    private fun updateInfor(){
        //模拟数据更新
        Thread.sleep(2000)
        mainHandler.post(object :Runnable{
            override fun run() {
                tv_content.text="每隔两秒更新一次数据：${Math.random()}"
            }
        })
    }

    override fun onResume() {
        super.onResume()
        needUpdate=true
        //开始发送
        sonHandler?.sendEmptyMessage(MSG_UPDATE_NUMBER)
    }

    override fun onPause() {
        super.onPause()
        //停止恒信
        needUpdate=false
        sonHandler?.removeMessages(MSG_UPDATE_NUMBER)
    }

    override fun onDestroy() {
        super.onDestroy()
        //释放资源
        handlerThread.quit()
    }
}
